import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// kv离线存储
class Storage {
  // 单例写法
  static final Storage _instance = Storage._internal();
  factory Storage() => _instance;
  late final SharedPreferences _sharedPreferences;

  Storage._internal();

  Future<void> init() async {
    try {
      _sharedPreferences = await SharedPreferences.getInstance();
      debugPrint("SharedPreferences初始化成功");
    } catch (e) {
      debugPrint("SharedPreferences初始化失败: $e");
      // 重试初始化
      await Future.delayed(const Duration(milliseconds: 500));
      _sharedPreferences = await SharedPreferences.getInstance();
    }
  }

  /// 存储JSON对象
  Future<bool> set_json(String key, Object value) async {
    try {
      final jsonString = jsonEncode(value);
      return await _sharedPreferences.setString(key, jsonString);
    } catch (e) {
      debugPrint('保存JSON失败，键：$key，错误：$e');
      return false;
    }
  }

  /// 存储字符串
  Future<bool> set_string(String key, String value) async {
    try {
      return await _sharedPreferences.setString(key, value);
    } catch (e) {
      debugPrint('保存字符串失败，键：$key，错误：$e');
      return false;
    }
  }

  /// 存储布尔值
  Future<bool> set_bool(String key, bool value) async {
    try {
      return await _sharedPreferences.setBool(key, value);
    } catch (e) {
      debugPrint('保存布尔值失败，键：$key，错误：$e');
      return false;
    }
  }

  /// 存储字符串列表
  Future<bool> set_list(String key, List<String> value) async {
    try {
      return await _sharedPreferences.setStringList(key, value);
    } catch (e) {
      debugPrint('保存列表失败，键：$key，错误：$e');
      return false;
    }
  }

  /// 获取字符串
  String? get_string(String key) {
    try {
      return _sharedPreferences.getString(key);
    } catch (e) {
      debugPrint('获取字符串失败，键：$key，错误：$e');
      return null;
    }
  }

  /// 获取布尔值，默认返回false
  bool get_bool(String key) {
    try {
      return _sharedPreferences.getBool(key) ?? false;
    } catch (e) {
      debugPrint('获取布尔值失败，键：$key，错误：$e');
      return false;
    }
  }

  /// 获取字符串列表，默认返回空列表
  List<String> get_list(String key) {
    try {
      return _sharedPreferences.getStringList(key) ?? [];
    } catch (e) {
      debugPrint('获取列表失败，键：$key，错误：$e');
      return [];
    }
  }

  /// 删除指定键的数据
  Future<bool> remove_data(String key) async {
    try {
      return await _sharedPreferences.remove(key);
    } catch (e) {
      debugPrint('删除数据失败，键：$key，错误：$e');
      return false;
    }
  }

  /// 获取JSON对象
  Map<String, dynamic>? get_json(String key) {
    try {
      final str = _sharedPreferences.getString(key);
      if (str == null || str.isEmpty) return null;
      return jsonDecode(str) as Map<String, dynamic>;
    } catch (e) {
      debugPrint('解析JSON失败，键：$key，错误：$e');
      return null;
    }
  }
}
